import React, { useEffect, useRef, useState } from 'react';
import { Button, DatePicker, Form, Message, Popconfirm, Select, Space } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import { connect } from 'umi';
import { useDebounceFn } from 'ahooks';

import { SyncOutlined, UploadOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading, TRDefault } from '@/components';
import { TjSegmented, TjStation } from '@/pages/ETrade/components';
import { useRem } from '@/hooks';

import { queryMarketList } from './services';
import {
  DIMENSION,
  DIMENSION96,
  DIMENSION_Month,
  PROVINCES,
  PROVINCES_MAP,
  TYPE_OPTIONS,
} from './helper';
import ComponentsList from './components/index'; // 不同省份业务组件
import styles from './index.less';
import { getTreeByCodes } from '@/utils';

let targetDate = [null, null];
// 当前日期大于当前月的2号
if (moment().diff(moment().startOf('month'), 'days') > 1) {
  targetDate = [moment().startOf('month'), moment()];
} else {
  targetDate = [
    moment().subtract(1, 'months').startOf('month'),
    moment().subtract(1, 'months').endOf('month'),
  ];
}

function ResumeAnalysis({ menuCode, buttonPermissions }) {
  const url = location.href;
  let queryUrlForm = {},
    hasUrlData = false;
  if (url.indexOf('?') != -1) {
    const [, value] = url.split('?');
    const [, urlValue] = value.split('=');
    queryUrlForm = JSON.parse(decodeURIComponent(urlValue));
    hasUrlData = !_.isEmpty(queryUrlForm);
  }
  let [spinning, setSpinning] = useState(true),
    [error, setError] = useState(''),
    [province, setProvince] = useState(''), // 切换省后选中的省份
    [regions, setRegions] = useState([]), // 全部省份
    [stations, setStations] = useState([]), // 全部场站（平铺）
    [regionsStations, setRegionsStations] = useState([]), // 对应省份场站（平铺）
    [stationTree, setStationTree] = useState([]), // 已选省份的场站树
    [dimensionEnum, setDimensionEnum] = useState(hasUrlData ? queryUrlForm.dimensionEnum : 1), // 0-默认维度 1-切换维度
    [tag, setTag] = useState(hasUrlData ? queryUrlForm.tag : '1'), // 1-测算数据 2-结算数据
    [pointNum, setPointNum] = useState(hasUrlData ? queryUrlForm.pointNum : '96'), // 时点
    [visible, setVisible] = useState(false), // 控制大数据查询前提示
    [type, setType] = useState(hasUrlData ? queryUrlForm.type : 0), // 交易单元类型
    [queryForm, setQueryForm] = useState(hasUrlData ? queryUrlForm : {}), // 记录查询时用的表单，批量导出有参数依赖
    [dateType, setDateType] = useState(queryUrlForm?.dataType || 'days');
  // [dataTypeOptions, setDataTypeOptions] = useState([]); //日期查询类型配置项;
  const [searchBtnLoading, setSearchBtnLoading] = useState(false);

  const contentRef = useRef(null);
  const [form] = Form.useForm();
  useRem(1920);

  // 初始化交易单元类型
  useEffect(() => {
    if (hasUrlData && regionsStations.length) {
      onTypeChange(queryUrlForm.type);
    } else {
      onTypeChange(0);
    }
  }, [regionsStations]);

  useEffect(() => {
    moment.updateLocale('zh-cn', {
      week: { dow: 5, doy: 4 },
    });
    init();
  }, []);

  /** handle data */
  async function init() {
    // 获取数据权限
    const res = await queryMarketList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      initDataPower(res?.json);
    } else {
      setError(res?.message || '系统异常');
    }
    setSpinning(false);
  }

  //初始化表单参数+默认请求
  const initialValues = (_regions, _stations) => {
    let initData = {};
    if (hasUrlData) {
      initData = {
        regions: queryUrlForm.regions,
        marketId: queryUrlForm.marketId,
        type: queryUrlForm.type,
        stationIds: queryUrlForm.stationIds,
        dateType: queryUrlForm.dateType,
        dateRange: [
          moment(queryUrlForm.startDate, 'YYYY-MM-DD'),
          moment(queryUrlForm.endDate, 'YYYY-MM-DD'),
        ],
      };
    } else {
      const stationsIds = _stations
        .filter((item) => item.marketId === _regions?.[0]?.marketId)
        ?.map((item) => item?.stationId || '');
      initData = {
        regions: _regions?.[0]?.provinceId,
        type: 0,
        dateType: 'days',
        dateRange: targetDate,
        stationIds: stationsIds,
        marketId: _regions?.[0]?.marketId,
      };
    }

    onRegionChange(initData.marketId);
    form.setFieldsValue(initData);
    onFinish(initData);
  };

  //重置
  const resetHanlder = () => {
    onRegionChange(hasUrlData ? queryUrlForm.marketId : regions?.[0]?.marketId);
    initialValues(regions, stations);
  };

  function initDataPower(data = []) {
    // 处理数据权限
    if (!data) {
      return;
    }
    const power = getTreeByCodes(['market', 'group', 'station'], data).treeOptions;
    stations = [];
    power.map((x) => {
      // 公司
      (x?.children || []).map((y) => {
        // 省份
        (y?.children || []).map((z) => {
          // 场站
          stations.push(z);
        });
      });
    });
    setRegions(power);
    setStations(stations);
    initialValues(power, stations);
  }

  const onChangeMarket = (value, opt) => {
    form.setFieldsValue({ stationIds: [], type: 0 });
    const _regionsStations = _.flatten(opt?.children?.map((i) => i?.children));
    setRegionsStations(_regionsStations);
    setProvince(opt.provinceId);
  };

  /** methods */
  // 切换省份
  const onRegionChange = (value) => {
    form.setFieldsValue({ stationIds: [], type: 0 });
    const _stations = stations.filter((i) => i.marketId === value);
    setRegionsStations(_stations);
    setProvince(value);
    // let _dateType;

    // if (value === PROVINCES.gansu) {
    //   const _dateTypeOptions = DATETYPEOPTION.filter((t) =>
    //     buttonPermissions.find((_t) => _t.menuCode === t.menuCode),
    //   );
    //   setDataTypeOptions(_dateTypeOptions);
    //   _dateType = _dateTypeOptions[0]?.value;
    // } else {
    //   _dateType = 'days';
    // }

    // onDateTypeChange(_dateType);
    // form.setFieldsValue({ dateType: _dateType });
  };

  // 筛选交易单元类型
  const onTypeChange = (val) => {
    form.setFieldsValue({ stationIds: [] });
    setType(val);
    stationTree = [];
    const _groups = _.groupBy(regionsStations, 'groupName');
    let selectAll = [];
    for (const key in _groups) {
      const _newGroup = [];
      for (const k in _groups[key]) {
        if (!val) {
          // 全部交易单元
          _newGroup.push(_groups[key][k]);
        }
        if (_groups[key][k].stationType === val) {
          // 选中的交易单元
          _newGroup.push(_groups[key][k]);
        }
      }
      selectAll = selectAll.concat(_newGroup.map((t) => t.stationId));
      if (_newGroup.length) {
        // 有交易单元的集团
        stationTree.push({
          title: key,
          key: Math.random(),
          children: _newGroup.map((item) => ({
            title: item.stationName,
            key: item.stationId,
            value: item.stationId,
          })),
        });
      }
    }
    form.setFieldsValue({ stationIds: selectAll });
    if (!val) setStationTree(stationTree);
  };

  // const onDateTypeChange = (e) => {
  //   form.setFieldsValue({
  //     dateRange: e === 'weeks' ? moment() : targetDate,
  //   });
  //   setDateType(e);
  // };

  const onFinish = async (values) => {
    setQueryForm({});
    // 查询
    const _stations = stations.filter((x) => values.marketId === x.marketId); // 根据stations中的数据取出省份，然后在取省份id
    const regionsName = _stations?.[0]?.provinceName;
    const isMonth = values.dateType === 'months';
    const params = {
      stationIds: values.stationIds.map((x) => x),
      provinceId: _stations?.[0].provinceId, // 根据stations中的数据取出省份，然后在取省份id
      tag,
      type,
      pointNum,
    };

    switch (values.dateType) {
      case 'months':
        params.startDate = moment(values.dateRange[0]).startOf('month').format('YYYY-MM-DD');
        params.endDate = moment(values.dateRange[1]).endOf('month').format('YYYY-MM-DD');
        break;
      case 'weeks':
        params.startDate = moment(values.dateRange).weekday(0).format('YYYY-MM-DD');
        params.endDate = moment(values.dateRange).weekday(6).format('YYYY-MM-DD');
        break;
      default:
        params.startDate = moment(values.dateRange[0]).format('YYYY-MM-DD');
        params.endDate = moment(values.dateRange[1]).format('YYYY-MM-DD');
    }
    if (queryUrlForm.dimension) {
      //子页面
      params.dimension = isMonth //按月查询
        ? dimensionEnum
          ? DIMENSION_Month['切换维度']
          : DIMENSION_Month['默认维度']
        : dimensionEnum
        ? DIMENSION96['切换维度']
        : DIMENSION96['默认维度'];
    } else {
      params.dimension = isMonth
        ? dimensionEnum
          ? DIMENSION_Month['切换维度']
          : DIMENSION_Month['默认维度']
        : dimensionEnum
        ? DIMENSION['切换维度']
        : DIMENSION['默认维度'];
    }

    const _groupIds = stations
      .filter((item) => item.marketId === values.marketId)
      ?.map((item) => item?.groupId || '');
    params.groupIds = [...new Set(_groupIds)];

    setQueryForm({
      ...params,
      dateType: values.dateType,
      regions: regionsName,
      dimensionEnum,
      marketId: values.marketId,
    });

    setTimeout(async () => {
      contentRef?.current?.onFetch?.();
    }, 0);
  };

  /** 山东图表数据配置 */

  const onChangeDimension = useDebounceFn(
    () => {
      setDimensionEnum(Number(!dimensionEnum));
      form.submit();
    },
    { wait: 500 },
  );

  const onexport = () => {
    const hasSave = buttonPermissions.find((item) => item.menuCode === 'ResumeAnalysisButtonWeb');
    if (!hasSave) {
      return Message.info('请联系管理员获取相关权限');
    }
    contentRef?.current?.onExport?.();
  };

  const confirm = useDebounceFn(
    () => {
      setVisible(false);
      form.submit();
    },
    { wait: 500 },
  );

  const handleVisibleChange = (newVisible) => {
    if (!newVisible) {
      setVisible(newVisible);
      return;
    }
    // 判断是否需要进行查询按钮的二次确认框
    const { stationIds, dateRange } = form.getFieldsValue();
    if (stationIds && dateType !== 'weeks' && dateRange) {
      const days = dateRange[1].diff(dateRange[0], 'days') + 1;
      if (days * stationIds.length > 900 && hasUrlData) {
        //
        setVisible(newVisible);
      } else {
        confirm.run();
      }
    } else {
      confirm.run();
    }
  };

  const _getDateSelectEl = (v) => {
    switch (v) {
      case 'weeks':
        return <DatePicker style={{ width: 240 }} picker="week" />;
      case 'months':
        return (
          <DatePicker.RangePicker
            style={{ width: 240 }}
            picker="month"
            placeholder={['开始日期', '结束日期']}
            format={'YYYYMM'}
            separator="-"
          />
        );
      default:
        return (
          <DatePicker.RangePicker
            style={{ width: 240 }}
            placeholder={['开始日期', '结束日期']}
            format={'YYYYMMDD'}
            separator="-"
          />
        );
    }
  };

  const _renderForm = () => {
    return (
      <Form name="query-form" form={form} layout="inline" onFinish={onFinish}>
        <Form.Item name="marketId" rules={[{ required: true, message: '交易中心不可为空!' }]}>
          <Select
            style={{ width: 200 }}
            options={regions}
            placeholder="交易中心"
            showSearch={true}
            showArrow={true}
            onChange={onChangeMarket}
            filterOption={(inp, option) => option.label.includes(inp)}
          />
        </Form.Item>
        <Form.Item name="type" rules={[{ required: true, message: '交易单元类型不可为空!' }]}>
          <Select
            style={{ width: 200 }}
            options={TYPE_OPTIONS}
            placeholder="交易单元类型"
            showArrow={true}
            onChange={onTypeChange}
          />
        </Form.Item>
        <Form.Item name="stationIds" rules={[{ required: true, message: '交易单元不可为空!' }]}>
          <TjStation options={stationTree} />
        </Form.Item>
        {/* {province === PROVINCES.gansu && dataTypeOptions.length ? (
          <Form.Item name="dateType" rules={[{ required: true, message: '日期类型不可为空!' }]}>
            <TjSegmented
              style={{ width: 160 }}
              onChange={onDateTypeChange}
              options={dataTypeOptions}
            />
          </Form.Item>
        ) : (
          ''
        )} */}
        <Form.Item name="dateRange" rules={[{ required: true, message: '日期不可为空!' }]}>
          {_getDateSelectEl(dateType)}
        </Form.Item>
        <Popconfirm
          title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
          visible={visible}
          onVisibleChange={handleVisibleChange}
          onConfirm={() => confirm.run()}
          onCancel={() => setVisible(false)}
          okText="确认"
          cancelText="取消"
        >
          <Button
            className={styles.search}
            type="primary"
            htmlType="submit"
            loading={searchBtnLoading}
          >
            查询
          </Button>
        </Popconfirm>
        <Button className={styles.search} onClick={resetHanlder} ghost loading={searchBtnLoading}>
          重置
        </Button>
      </Form>
    );
  };
  const _renderContent = () => {
    if (!queryForm?.provinceId) return null;
    const ContentCompt =
      ComponentsList?.['PROVINCE_' + (PROVINCES_MAP[queryForm.provinceId] ?? PROVINCES_MAP[14])];
    const contentProps = {
      stations,
      tag,
      queryForm,
      queryUrlForm,
      hasUrlData,
      dimensionEnum,
      menuCode,
      regions,
      changeSearchBtnLoading: (flag) => {
        setSearchBtnLoading(flag);
      },
      fetchData: () => {
        form.submit();
      },
    };
    return <ContentCompt ref={contentRef} {...contentProps} />;
  };

  if (spinning) return <PageLoading />;
  if (error) return <TRDefault type="error" message={error} />;
  if (!stations?.length) return <TRDefault type="lock" />;
  return (
    <div className={styles.container}>
      {/* 顶部工具栏 */}
      <div className={styles.toolbar}>
        <div>{_renderForm()}</div>
        <div>
          <Space size={16}>
            {[PROVINCES.shandong, PROVINCES.gansu, PROVINCES.mengxi, PROVINCES.hubei].includes(
              province,
            ) ||
            (hasUrlData && [PROVINCES.shanxi].includes(province)) ? (
              <TjSegmented
                value={pointNum}
                options={[
                  { label: '24', value: '24' },
                  { label: '96', value: '96' },
                ]}
                onChange={(e) => {
                  setPointNum(e);
                  form.submit();
                }}
              />
            ) : null}

            {![PROVINCES.shandong, PROVINCES.gansu, PROVINCES.hubei].includes(province) && (
              <div className={styles.tag}>
                <TjSegmented
                  value={tag}
                  options={[
                    { label: '测算数据', value: '1' },
                    { label: '结算数据', value: '2' },
                  ]}
                  onChange={(e) => {
                    setTag(e);
                    form.submit();
                  }}
                />
              </div>
            )}
            {/* {![PROVINCES.shandong, PROVINCES.gansu, PROVINCES.mengxi, PROVINCES.hubei].includes(
              province,
            ) ? (
              <a className={styles.change} onClick={() => onChangeDimension.run()}>
                <SyncOutlined style={{ fontSize: 14, marginRight: 5 }} />
                切换维度
              </a>
            ) : null} */}
            <a className={styles.export} onClick={onexport}>
              <UploadOutlined style={{ fontSize: 14, marginRight: 5 }} />
              导出
            </a>
          </Space>
        </div>
      </div>
      <div className={styles.contentAll}>{_renderContent()}</div>
    </div>
  );
}
export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(ResumeAnalysis);
